/** @format */

const express = require("express");
const cors = require("cors");
const multer = require("multer");
const path = require("path");

const app = express();
app.use(cors());
app.use(express.static("public"));
app.get("/", (req, res) => {
  //   res.status(200).json({
  //     code: 200,
  //     msg: "Hello Express !",
  //   });

  res.send("Hello");
});

// const upload = multer({ dest: "uploads" });
// app.post("/fileUpload", upload.single("fileUpload"), function (req, res, next) {
//   console.log("req.file", req.file);
//   console.log("req.body", req.body);
//   res.status(200).json({
//     code: 200,
//     msg: "upload success !",
//   });
// });

// app.post("/fileUploads", upload.array("fileUploads", 2), function (req, res, next) {
//   console.log("req.file", req.files);
//   console.log("req.body", req.body);
//   res.status(200).json({
//     code: 200,
//     msg: "upload files success !",
//   });
// });

// app.post(
//   "/fileUploads",
//   upload.fields([
//     { name: "aaa", maxCount: 2 },
//     { name: "bbb", maxCount: 2 },
//   ]),
//   function (req, res, next) {
//     console.log("req.file", req.files);
//     console.log("req.body", req.body);
//     res.status(200).json({
//       code: 200,
//       msg: "upload files success !",
//     });
//   }
// );

const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    try {
      fs.mkdirSync(path.join(process.cwd(), "my-uploads"));
    } catch (e) {}
    cb(null, path.join(process.cwd(), "my-uploads"));
  },
  filename: function (req, file, cb) {
    const uniqueSuffix = Date.now() + "-" + Math.round(Math.random() * 1e9) + "-" + file.originalname;
    cb(null, file.fieldname + "-" + uniqueSuffix);
  },
});
const upload = multer({ storage });
app.post("/fileUploads", upload.any(), function (req, res, next) {
  console.log("req.file", req.files);
  console.log("req.body", req.body);
  res.status(200).json({
    code: 200,
    msg: "upload files success !",
  });
});

app.listen(3000, () => {
  console.log(`server start at http://localhost:3000`);
});
